using Microsoft.AspNetCore.Mvc;
using Product.Service;
using hao_Dto;
using hao_Common.Response.Extensions;
using hao_Common.Consul.Services;
using Microsoft.AspNetCore.Authorization;
using System.Text.Json;
using hao_Model;
using System.Linq;

namespace hao_Product.Api.Controllers
{
    /// <summary>
    /// 商品管理控制器
    /// </summary>
    [ApiController]
    [Route("api/product")]
    public class ProductController : ControllerBase
    {
        private readonly IProductService _productService;
        private readonly IServiceDiscovery _serviceDiscovery;
        private readonly HttpClient _httpClient;
        private readonly ILogger<ProductController> _logger;
        private readonly IProductCommentService _commentService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productService">商品服务</param>
        /// <param name="serviceDiscovery">服务发现</param>
        /// <param name="httpClient">HTTP客户端</param>
        /// <param name="logger">日志记录器</param>
        public ProductController(
            IProductService productService,
            IServiceDiscovery serviceDiscovery,
            HttpClient httpClient,
            ILogger<ProductController> logger,
            IProductCommentService commentService)
        {
            _productService = productService;
            _serviceDiscovery = serviceDiscovery;
            _httpClient = httpClient;
            _logger = logger;
            _commentService = commentService;
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="dto">商品发布信息</param>
        /// <returns>添加结果</returns>
        /// <response code="200">添加成功</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="401">未授权</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("add")]
        [Authorize]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(401)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> AddProduct([FromBody] ProductPublishDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return this.ValidationFailResult("请求参数无效");

                // 获取当前用户ID
                var userId = GetCurrentUserId();

                var productId = await _productService.AddProductAsync(dto, userId);
                return this.SuccessResult(new { id = productId }, "商品添加成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加商品失败");
                return this.ServerErrorResult("添加商品失败");
            }
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>商品详情</returns>
        /// <response code="200">获取成功</response>
        /// <response code="404">商品不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{id}")]
        [ProducesResponseType(typeof(ProductResponseDto), 200)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetProduct(Guid id)
        {
            try
            {
                var product = await _productService.GetProductByIdAsync(id);
                return product == null 
                    ? this.NotFoundResult("商品不存在") 
                    : this.SuccessResult(product, "获取商品详情成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取商品详情失败，ID: {ProductId}", id);
                return this.ServerErrorResult("获取商品详情失败");
            }
        }

        /// <summary>
        /// 获取商品列表（分页）
        /// </summary>
        /// <param name="page">页码，默认为1</param>
        /// <param name="pageSize">每页数量，默认为10，最大100</param>
        /// <param name="category">商品分类筛选</param>
        /// <param name="keyword">关键词搜索</param>
        /// <returns>商品列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("list")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetProducts(
            [FromQuery] int page = 1, 
            [FromQuery] int pageSize = 10,
            [FromQuery] string? category = null,
            [FromQuery] string? keyword = null)
        {
            try
            {
                page = Math.Max(1, page);
                pageSize = Math.Clamp(pageSize, 1, 100);

                var (products, total) = await _productService.GetProductsAsync(page, pageSize, category, keyword);
                
                var result = new
                {
                    products,
                    pagination = new
                    {
                        page,
                        pageSize,
                        total,
                        totalPages = (int)Math.Ceiling((double)total / pageSize)
                    }
                };

                return this.SuccessResult(result, "获取商品列表成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取商品列表失败");
                return this.ServerErrorResult("获取商品列表失败");
            }
        }

        /// <summary>
        /// 添加或更新商品信息
        /// </summary>
        /// <param name="dto">商品信息</param>
        /// <returns>操作结果</returns>
        /// <response code="200">操作成功</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="401">未授权</response>
        /// <response code="404">商品不存在（仅更新时）</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("save")]
        [Authorize]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(401)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> SaveProduct([FromBody] ProductPublishDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return this.ValidationFailResult("请求参数无效");

                // 获取当前用户ID
                var userId = GetCurrentUserId();

                if (dto.Id.HasValue && dto.Id.Value != Guid.Empty)
                {
                    // 更新商品
                    var success = await _productService.UpdateProductAsync(dto.Id.Value, dto);
                    return success 
                        ? this.SuccessResult(new { id = dto.Id.Value }, "商品更新成功")
                        : this.NotFoundResult("商品不存在或已删除");
                }
                else
                {
                    // 新增商品
                    var productId = await _productService.AddProductAsync(dto, userId);
                    return this.SuccessResult(new { id = productId }, "商品添加成功");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存商品失败");
                return this.ServerErrorResult("保存商品失败");
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>删除结果</returns>
        /// <response code="200">删除成功</response>
        /// <response code="401">未授权</response>
        /// <response code="404">商品不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpDelete("{id}")]
        [Authorize]
        [ProducesResponseType(200)]
        [ProducesResponseType(401)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> DeleteProduct(Guid id)
        {
            try
            {
                var success = await _productService.DeleteProductAsync(id);
                return success 
                    ? this.SuccessResult("商品删除成功")
                    : this.NotFoundResult("商品不存在");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除商品失败，ID: {ProductId}", id);
                return this.ServerErrorResult("删除商品失败");
            }
        }

        /// <summary>
        /// 根据用户ID获取商品列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户的商品列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="401">未授权</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("user/{userId}")]
        [Authorize]
        [ProducesResponseType(typeof(List<ProductListDto>), 200)]
        [ProducesResponseType(401)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetProductsByUserId(Guid userId)
        {
            try
            {
                var products = await _productService.GetProductsByUserIdAsync(userId);
                return this.SuccessResult(products, "获取用户商品列表成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户商品列表失败，用户ID: {UserId}", userId);
                return this.ServerErrorResult("获取用户商品列表失败");
            }
        }

        /// <summary>
        /// 搜索商品
        /// </summary>
        /// <param name="keyword">搜索关键词</param>
        /// <param name="page">页码，默认为1</param>
        /// <param name="pageSize">每页数量，默认为10，最大100</param>
        /// <returns>搜索结果</returns>
        /// <response code="200">搜索成功</response>
        /// <response code="400">搜索关键词不能为空</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("search")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> SearchProducts(
            [FromQuery] string keyword,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(keyword))
                    return this.ValidationFailResult("搜索关键词不能为空");

                page = Math.Max(1, page);
                pageSize = Math.Clamp(pageSize, 1, 100);

                var (products, total) = await _productService.SearchProductsAsync(keyword, page, pageSize);
                
                var result = new
                {
                    products,
                    pagination = new
                    {
                        page,
                        pageSize,
                        total,
                        totalPages = (int)Math.Ceiling((double)total / pageSize)
                    },
                    keyword
                };

                return this.SuccessResult(result, "搜索商品成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索商品失败，关键词: {Keyword}", keyword);
                return this.ServerErrorResult("搜索商品失败");
            }
        }

        /// <summary>
        /// 获取商品图片
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>商品图片URL列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{id}/images")]
        [ProducesResponseType(typeof(List<string>), 200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetProductImages(Guid id)
        {
            try
            {
                var images = await _productService.GetProductImagesAsync(id);
                var imageUrls = images.Select(img => img.Url).ToList();
                
                return this.SuccessResult(imageUrls, "获取商品图片成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取商品图片失败，ID: {ProductId}", id);
                return this.ServerErrorResult("获取商品图片失败");
            }
        }

        /// <summary>
        /// 测试接口
        /// </summary>
        /// <returns>测试结果</returns>
        /// <response code="200">服务正常</response>
        [HttpGet("test")]
        [ProducesResponseType(typeof(object), 200)]
        public IActionResult Test()
        {
            return this.SuccessResult(new { message = "Product API is working!", timestamp = DateTime.UtcNow }, "服务正常");
        }

        /// <summary>
        /// 健康检查端点
        /// </summary>
        /// <returns>服务健康状态</returns>
        /// <response code="200">服务正常</response>
        [HttpGet("health")]
        [ProducesResponseType(typeof(object), 200)]
        public IActionResult Health()
        {
            return this.SuccessResult(new { status = "healthy", timestamp = DateTime.UtcNow }, "服务正常");
        }

        #region 服务发现相关接口

        /// <summary>
        /// 获取用户信息（通过服务发现调用User服务）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户信息</returns>
        /// <response code="200">获取成功</response>
        /// <response code="503">用户服务不可用</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("user-info/{userId}")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(503)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetUserInfo(Guid userId)
        {
            try
            {
                var userServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-user-api");
                
                if (string.IsNullOrEmpty(userServiceUrl))
                {
                    _logger.LogWarning("用户服务不可用");
                    return StatusCode(503, new { message = "用户服务不可用" });
                }

                var response = await _httpClient.GetAsync($"{userServiceUrl}/api/user/{userId}");
                
                if (response.IsSuccessStatusCode)
                {
                    var userInfo = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation("成功获取用户信息: {UserId}", userId);
                    return Ok(JsonSerializer.Deserialize<object>(userInfo));
                }
                
                _logger.LogWarning("调用用户服务失败: {StatusCode}", response.StatusCode);
                return StatusCode((int)response.StatusCode, new { message = "调用用户服务失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户信息时发生错误: {UserId}", userId);
                return StatusCode(500, new { message = $"服务发现失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取所有可用的服务实例
        /// </summary>
        /// <returns>服务实例列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("services")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetAvailableServices()
        {
            try
            {
                var userServiceInstances = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-user-api");
                var productServiceInstances = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-product-api");
                
                return Ok(new 
                {
                    message = "获取服务实例成功",
                    services = new
                    {
                        userService = userServiceInstances,
                        productService = productServiceInstances
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取服务实例时发生错误");
                return StatusCode(500, new { message = $"获取服务实例失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 验证用户权限（通过服务发现调用User服务）
        /// </summary>
        /// <param name="loginData">登录数据</param>
        /// <returns>验证结果</returns>
        /// <response code="200">验证成功</response>
        /// <response code="503">用户服务不可用</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("verify-user")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(503)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> VerifyUser([FromBody] object loginData)
        {
            try
            {
                var userServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-user-api");
                
                if (string.IsNullOrEmpty(userServiceUrl))
                {
                    return StatusCode(503, new { message = "用户服务不可用" });
                }

                var jsonContent = new StringContent(
                    JsonSerializer.Serialize(loginData),
                    System.Text.Encoding.UTF8,
                    "application/json");

                var response = await _httpClient.PostAsync($"{userServiceUrl}/api/user/login", jsonContent);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    return Ok(JsonSerializer.Deserialize<object>(result));
                }
                
                return StatusCode((int)response.StatusCode, new { message = "用户验证失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证用户时发生错误");
                return StatusCode(500, new { message = $"用户验证失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 测试调用订单服务 - 获取用户订单
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户订单信息</returns>
        [HttpGet("test/user-orders/{userId}")]
        public async Task<IActionResult> TestGetUserOrders(Guid userId)
        {
            try
            {
                var orderServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-order-api");
                
                if (string.IsNullOrEmpty(orderServiceUrl))
                {
                    _logger.LogWarning("订单服务不可用");
                    return StatusCode(503, new { message = "订单服务不可用" });
                }

                var response = await _httpClient.GetAsync($"{orderServiceUrl}/api/order/buyer/{userId}");
                
                if (response.IsSuccessStatusCode)
                {
                    var orderInfo = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation("成功获取用户订单信息: {UserId}", userId);
                    return Ok(new 
                    {
                        serviceUrl = orderServiceUrl,
                        orders = JsonSerializer.Deserialize<object>(orderInfo)
                    });
                }
                
                _logger.LogWarning($"调用订单服务失败: {response.StatusCode}");
                return StatusCode((int)response.StatusCode, new { message = "获取订单信息失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户订单时发生错误: {UserId}", userId);
                return StatusCode(500, new { message = $"获取用户订单失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 测试服务发现 - 获取所有可用服务实例
        /// </summary>
        /// <returns>所有服务实例信息</returns>
        [HttpGet("test/services")]
        public async Task<IActionResult> TestGetAllServices()
        {
            try
            {
                var userServices = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-user-api");
                var orderServices = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-order-api");
                var productServices = await _serviceDiscovery.GetHealthyServiceInstancesAsync("hao-product-api");

                return Ok(new 
                {
                    services = new
                    {
                        userService = userServices,
                        orderService = orderServices,
                        productService = productServices
                    },
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取服务实例时发生错误");
                return StatusCode(500, new { message = $"获取服务实例失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 综合测试 - 模拟商品发布时的服务调用
        /// </summary>
        /// <param name="testProduct">测试商品信息</param>
        /// <returns>测试结果</returns>
        [HttpPost("test/publish-simulation")]
        public async Task<IActionResult> TestProductPublishSimulation([FromBody] TestProductDto testProduct)
        {
            try
            {
                var results = new List<object>();

                // 1. 调用用户服务验证用户
                try
                {
                    var userServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-user-api");
                    if (!string.IsNullOrEmpty(userServiceUrl))
                    {
                        var userResponse = await _httpClient.GetAsync($"{userServiceUrl}/api/user/{testProduct.UserId}");
                        if (userResponse.IsSuccessStatusCode)
                        {
                            var userInfo = await userResponse.Content.ReadAsStringAsync();
                            results.Add(new { service = "user", status = "success", data = JsonSerializer.Deserialize<object>(userInfo) });
                        }
                        else
                        {
                            results.Add(new { service = "user", status = "error", message = $"HTTP {userResponse.StatusCode}" });
                        }
                    }
                    else
                    {
                        results.Add(new { service = "user", status = "unavailable" });
                    }
                }
                catch (Exception ex)
                {
                    results.Add(new { service = "user", status = "error", message = ex.Message });
                }

                // 2. 检查订单服务是否可用（商品发布后可能需要处理相关订单）
                try
                {
                    var orderServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-order-api");
                    if (!string.IsNullOrEmpty(orderServiceUrl))
                    {
                        var orderResponse = await _httpClient.GetAsync($"{orderServiceUrl}/api/order/test/services");
                        if (orderResponse.IsSuccessStatusCode)
                        {
                            results.Add(new { service = "order", status = "available" });
                        }
                        else
                        {
                            results.Add(new { service = "order", status = "error", message = $"HTTP {orderResponse.StatusCode}" });
                        }
                    }
                    else
                    {
                        results.Add(new { service = "order", status = "unavailable" });
                    }
                }
                catch (Exception ex)
                {
                    results.Add(new { service = "order", status = "error", message = ex.Message });
                }

                return Ok(new 
                {
                    testProduct = testProduct,
                    serviceCallResults = results,
                    timestamp = DateTime.Now,
                    message = "商品发布模拟测试完成"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "商品发布模拟测试失败");
                return StatusCode(500, new { message = $"商品发布模拟测试失败: {ex.Message}" });
            }
        }

        #endregion

        #region 商品留言相关接口

        /// <summary>
        /// 获取商品留言列表
        /// </summary>
        /// <param name="productId">商品ID</param>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>留言列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="400">参数错误</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{productId}/comments")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetProductComment(
            Guid productId,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                var queryDto = new hao_Dto.Product.ProductCommentQueryDto
                {
                    ProductId = productId,
                    Page = page,
                    PageSize = pageSize
                };

                // 获取当前用户ID（如果已登录）
                Guid? currentUserId = null;
                if (User.Identity.IsAuthenticated)
                {
                    var userIdClaim = User.FindFirst("UserId")?.Value;
                    if (Guid.TryParse(userIdClaim, out var userId))
                    {
                        currentUserId = userId;
                    }
                }

                var result = await _commentService.GetCommentsAsync(queryDto, currentUserId);
                return this.SuccessResult(result, "获取留言列表成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取商品留言列表失败: {ProductId}", productId);
                return this.ServerErrorResult($"获取留言列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 创建商品留言
        /// </summary>
        /// <param name="productId">商品ID</param>
        /// <param name="createDto">创建留言DTO</param>
        /// <returns>创建的留言</returns>
        /// <response code="200">创建成功</response>
        /// <response code="400">参数错误</response>
        /// <response code="401">未授权</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("{productId}/comments")]
        [Authorize]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(401)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> CreateProductComment(
            Guid productId,
            [FromBody] hao_Dto.Product.CreateProductCommentDto createDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return this.ValidationFailResult("参数验证失败");
                }

                // 确保DTO中的ProductId与路由参数一致
                createDto.ProductId = productId;

                // 获取当前用户ID
                var userIdClaim = User.FindFirst("UserId")?.Value;
                if (!Guid.TryParse(userIdClaim, out var userId))
                {
                    return this.ValidationFailResult("用户身份验证失败");
                }

                var result = await _commentService.CreateCommentAsync(createDto, userId);
                return this.SuccessResult(result, "留言创建成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建商品留言失败: {ProductId}, {UserId}", productId, User.FindFirst("UserId")?.Value);
                return this.ServerErrorResult($"创建留言失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 点赞/取消点赞留言
        /// </summary>
        /// <param name="commentId">留言ID</param>
        /// <returns>点赞状态</returns>
        /// <response code="200">操作成功</response>
        /// <response code="401">未授权</response>
        /// <response code="404">留言不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("comments/{commentId}/like")]
        [Authorize]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(401)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> ToggleCommentLike(Guid commentId)
        {
            try
            {
                // 获取当前用户ID
                var userIdClaim = User.FindFirst("UserId")?.Value;
                if (!Guid.TryParse(userIdClaim, out var userId))
                {
                    return this.ValidationFailResult("用户身份验证失败");
                }

                var isLiked = await _commentService.ToggleLikeAsync(commentId, userId);
                return this.SuccessResult(new { isLiked }, isLiked ? "点赞成功" : "取消点赞成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "点赞操作失败: {CommentId}, {UserId}", commentId, User.FindFirst("UserId")?.Value);
                return this.ServerErrorResult($"点赞操作失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 取消点赞留言
        /// </summary>
        /// <param name="commentId">留言ID</param>
        /// <returns>操作结果</returns>
        /// <response code="200">操作成功</response>
        /// <response code="401">未授权</response>
        /// <response code="500">服务器内部错误</response>
        [HttpDelete("comments/{commentId}/like")]
        [Authorize]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(401)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> RemoveCommentLike(Guid commentId)
        {
            try
            {
                // 获取当前用户ID
                var userIdClaim = User.FindFirst("UserId")?.Value;
                if (!Guid.TryParse(userIdClaim, out var userId))
                {
                    return this.ValidationFailResult("用户身份验证失败");
                }

                var isLiked = await _commentService.ToggleLikeAsync(commentId, userId);
                return this.SuccessResult(new { isLiked = false }, "取消点赞成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "取消点赞失败: {CommentId}, {UserId}", commentId, User.FindFirst("UserId")?.Value);
                return this.ServerErrorResult($"取消点赞失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除留言
        /// </summary>
        /// <param name="commentId">留言ID</param>
        /// <returns>删除结果</returns>
        /// <response code="200">删除成功</response>
        /// <response code="401">未授权</response>
        /// <response code="403">无权限</response>
        /// <response code="404">留言不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpDelete("comments/{commentId}")]
        [Authorize]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(401)]
        [ProducesResponseType(403)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> DeleteComment(Guid commentId)
        {
            try
            {
                // 获取当前用户ID
                var userIdClaim = User.FindFirst("UserId")?.Value;
                if (!Guid.TryParse(userIdClaim, out var userId))
                {
                    return this.ValidationFailResult("用户身份验证失败");
                }

                var result = await _commentService.DeleteCommentAsync(commentId, userId);
                if (!result)
                {
                    return this.NotFoundResult("无权限删除此留言或留言不存在");
                }

                return this.SuccessResult<object>(null, "删除留言成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除留言失败: {CommentId}, {UserId}", commentId, User.FindFirst("UserId")?.Value);
                return this.ServerErrorResult($"删除留言失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户的留言列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>用户留言列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("user/{userId}/comments")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetUserComments(
            Guid userId,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                // 这里需要实现获取用户留言的逻辑
                // 由于当前仓储接口没有按用户ID查询的方法，这里返回模拟数据
                var mockComments = new
                {
                    comments = new[]
                    {
                        new
                        {
                            id = Guid.NewGuid(),
                            productId = Guid.NewGuid(),
                            productTitle = "测试商品1",
                            content = "这个商品很不错",
                            createdAt = DateTime.UtcNow.AddDays(-1),
                            likeCount = 5
                        },
                        new
                        {
                            id = Guid.NewGuid(),
                            productId = Guid.NewGuid(),
                            productTitle = "测试商品2",
                            content = "质量很好，推荐购买",
                            createdAt = DateTime.UtcNow.AddDays(-2),
                            likeCount = 3
                        }
                    },
                    total = 2,
                    page = page,
                    pageSize = pageSize,
                    totalPages = 1
                };

                return this.SuccessResult(mockComments, "获取用户留言成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户留言失败: {UserId}", userId);
                return this.ServerErrorResult($"获取用户留言失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取用户的留言统计信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>留言统计</returns>
        /// <response code="200">获取成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("user/{userId}/comments/stats")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetUserCommentStats(Guid userId)
        {
            try
            {
                // 返回用户留言统计的模拟数据
                var mockStats = new
                {
                    totalComments = 15,
                    totalLikes = 42,
                    totalReplies = 8,
                    recentComments = 3,
                    mostLikedComment = new
                    {
                        id = Guid.NewGuid(),
                        content = "这个商品真的很棒！",
                        likeCount = 12,
                        productTitle = "热门商品"
                    }
                };

                return this.SuccessResult(mockStats, "获取用户留言统计成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户留言统计失败: {UserId}", userId);
                return this.ServerErrorResult($"获取用户留言统计失败: {ex.Message}");
            }
        }

        #endregion

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        private Guid GetCurrentUserId()
        {
            var userIdClaim = User.FindFirst("UserId")?.Value;
            if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
            {
                throw new UnauthorizedAccessException("用户未登录或用户ID无效");
            }
            return userId;
        }
    }

    /// <summary>
    /// 测试商品DTO
    /// </summary>
    public class TestProductDto
    {
        public Guid UserId { get; set; }
        public string Title { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public string Category { get; set; } = string.Empty;
        public decimal Price { get; set; }
        public string Location { get; set; } = string.Empty;
    }
}
